﻿using ChoWorkflowServer.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ChoWorkflowServer
{
    public class ChoDelayFireDependencyTaskScheduler
    {
        private readonly object _padLock = new object();
        private readonly Dictionary<string, Tuple<CancellationTokenSource, Task>> _scheduledTasks = new Dictionary<string, Tuple<CancellationTokenSource, Task>>();

        public void ScheduleTask(int batchId, string taskName, string scheduleName, string workflowName, int fireAfter)
        {
            lock (_padLock)
            {
                string jobName = ChoJobNameHelper.ToJobName(taskName, scheduleName);

                if (_scheduledTasks.ContainsKey(jobName))
                    CancelTask(taskName, scheduleName);

                var ts = new CancellationTokenSource();

                _scheduledTasks.Add(jobName, new Tuple<CancellationTokenSource, Task>(ts, Task.Run(async delegate
                {
                    if (!ts.IsCancellationRequested)
                        await Task.Delay(fireAfter * 60 * 1000, ts.Token);
                    if (!ts.IsCancellationRequested)
                        ChoWorkflowServerEx.Instance.FireStartTask(batchId, taskName, scheduleName, workflowName, ChoUser.SYSTEM_ACCT, Environment.MachineName);
                })));
            }
        }

        public void CancelTask(string taskName, string scheduleName)
        {
            lock (_padLock)
            {
                string jobName = ChoJobNameHelper.ToJobName(taskName, scheduleName);

                if (!_scheduledTasks.ContainsKey(jobName))
                    return;

                Tuple<CancellationTokenSource, Task> tuple = _scheduledTasks[jobName];
                tuple.Item1.Cancel();
                _scheduledTasks.Remove(jobName);
            }
        }
    }
}
